/*
 * @Date: 2023-03-01 22:29:57
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-12-28 09:22:57
 * @ axios 二次封装
 */
import axios from 'axios'
interface postFormData {
  url: String
  data?: Object
  params?: Object
  withCredentials?: Boolean
}

export default class httpRequest {
  baseURL: string
  static request: any

  constructor(baseURL: string) {
    this.baseURL = baseURL
  }

  // 默认配置
  getDefaultConfig() {
    const config = {
      baseURL: this.baseURL,
      timeout: 5000,
      headers: { 'content-type': 'application/x-www-form-urlencoded' }
    }
    return config
  }

  // 创建axios
  request(options: Object) {
    const instance = axios.create()
    options = Object.assign({}, this.getDefaultConfig(), options)

    // 请求拦截
    instance.interceptors.request.use(
      (config) => {
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    // 响应拦截
    instance.interceptors.response.use(
      (response) => {
        return response.data
      },
      (error) => {
        return Promise.reject(error.message)
      }
    )

    return instance(options)
  }

  get(options: postFormData) {
    return this.request({
      method: 'GET',
      ...options
    })
  }

  post(options: postFormData) {
    return this.request({
      method: 'POST',
      ...options
    })
  }

  // postFormData(options: postFormData) {
  //   const formData = new FormData();
  //   for (let key in options.data) {
  //     formData.append(key, options.data[key]);
  //   }
  //   return this.request({
  //     methods: "POST",
  //     headers: { "Content-Type": "multipart/form-data" },
  //     ...options,
  //     data: formData,
  //   });
  // }
}
